/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-03-23
 * Time: 16:54
 */


//饿汉~类一旦加载就实例整个对象
class Singleton {
    private static Singleton instance = new Singleton();//特殊的语法场景
    //该属性是类的属性（类对象上）
    //jvm中，类对象只有一份~
    //那么instance就仅此一份了~
    //在外部打破单例，就必须通过不常规操作，反射~
    //但是可以用枚举类型，完美的单例
    //反射是不常规的！！！是为了特定的特殊场景，【破例】去访问private
    //就相当于，我的世界，【这是最后一次开创造~】
    public static Singleton getInstance() {
        return instance;
    }
    //禁止外界new操作
    //利用语法特点~比抛异常要好一点~
    //抛异常闷声禁止，并且比较麻烦~
    //不如从语法层面就禁止~
    //保证单例模式的特性，“初心”“针对性”
    private Singleton() {

    }
}



class SingletonLazy {
    volatile private static SingletonLazy singletonLazy = null;

    public static SingletonLazy getSingletonLazy() {
        if(singletonLazy == null) {
            synchronized (SingletonLazy.class) {
                if(singletonLazy == null) {
                    singletonLazy = new SingletonLazy();
                }
            }
        }
        return singletonLazy;
    }
    private SingletonLazy() {

    }
}





public class Test {


    public static void main2(String[] args) {
        SingletonLazy s1 = SingletonLazy.getSingletonLazy();
        SingletonLazy s2 = SingletonLazy.getSingletonLazy();
        System.out.println(s1 == s2);
    }



    public static void main1(String[] args) {
        Singleton s1 = Singleton.getInstance();
        //Singleton s2 = new Singleton();报错~
    }
}
